package com.first.orange.service.impl;

import com.first.orange.beans.*;
import com.first.orange.mapper.PersonMapper;
import com.first.orange.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created on 2021/7/5.
 * <p>
 * Author : Lcywings
 * <p>
 * Description : 个人中心业务实现类
 */
@Service
public class PersonServiceImpl implements PersonService {

    //个人中心数据接口
    @Autowired(required = false)
    PersonMapper personMapper;


    @Override
    //获取个人资产业务实现
    public Map<String, Object> getPersonalAssets(Integer userId) {
        //声明个人资产map
        Map<String, Object> map = new HashMap<>();

        //声明用户信息详情类
        UserInformation userInformation = personMapper.getUserInformation(userId);

        // 获取用户信息详情
        map.put("userInformation", userInformation);
        // 获取账户优惠券数量
        if (null == personMapper.getCouponTotal(userId)) {
            map.put("couponTotal", 2);
        } else {
            map.put("couponTotal", personMapper.getCouponTotal(userId));
        }
        // 返回数据
        return map;
    }

    @Override
    public List<Orders> getOrders(Integer userId) {
        return personMapper.getOrders(userId);
    }

    @Override
    public Product getProduct(Integer productId) {
        return personMapper.getProduct(productId);
    }

    @Override
    public void updatePerson(UserInformation userInformation) {
        // 更新用户信息
        personMapper.modPerson(userInformation);
    }

    @Override
    public void updatePassword(Integer userId, String possword) {
        personMapper.updatePassword(userId, possword);
    }

    @Override
    public Boolean checkedPassword(String password1, String password2) {
        if (null == password1 || "".equals(password1))
            return false;
        if (null == password2 || "".equals(password2))
            return false;
        if (password1.equals(password2))
            return true;
        return false;
    }

    @Override
    public UserLogin selectUserLogin(Integer userId) {
        return personMapper.selectUserLoginByUserId(userId);
    }

    @Override
    public Boolean uploadPic(MultipartFile multipartFile, Integer userId, HttpSession session) {
        // 获取到上传文件的名称
        String fileName = multipartFile.getOriginalFilename();

        // 获取服务器上传文件的真实路径(还可以指定服务器的固定目录)
        String realPath = session.getServletContext().getRealPath("img");
        String savePath = "../img";
        System.out.println(realPath);

        // 创建文件对象
        File file = new File(realPath);
        // 判断目录是否存在，如果不存在，就创建目标目录，如果存在就直接使用
        if (!file.exists()) {
            if (file.mkdirs()) {
                System.out.println("目标目录不存在，创建成功！");
            } else {
                System.out.println("目标目录不存在，创建失败！");
            }
        }

        // 创建一个目标文件对象
        File targeFile = new File(realPath + "/" + fileName);

        //文件Url
        String userProfile = savePath + "/" + fileName;
        //将文件Url存到数据库
        personMapper.updateUserPic(userProfile, userId);

        try {
            // 高级用法
            multipartFile.transferTo(targeFile);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public List<UserFootprint> queryUserFootByUserId(Integer userId) {
        return personMapper.selectUserFootByUserId(userId);
    }

    @Override
    public Product queryProductByproductId(Integer productId) {
        return personMapper.selectProductByproductId(productId);
    }

    @Override
    public void deleteFootByuserIdAnd(Integer footPrintId, Integer userId) {
        personMapper.deleteFootByuserIdAnd(footPrintId, userId);
    }

    @Override
    public List<UserCollection> queryUserCollectionByUserId(Integer userId) {
        return personMapper.queryUserCollectionByUserId(userId);
    }

    @Override
    public void deleteCollectionByUserIdAndCollectionId(Integer collectionId, Integer userId) {
        personMapper.deleteCollectionByUserIdAndCollectionId(collectionId, userId);
    }

    @Override
    public List<ShopAddress> getShopAddressByUserId(Integer userId) {
        return personMapper.getShopAddressByUserId(userId);
    }

    @Override
    public void deleteAddrByUserIdAndShopId(Integer shopId, Integer userId) {
        personMapper.deleteAddrByUserIdAndShopId(shopId, userId);
    }

    @Override
    public void insertShopAddressByUserId(ShopAddress shopAddress) {
        personMapper.insertShopAddressByUserId(shopAddress);
    }

    @Override
    public void setDefShopIdByUserIdAndShopId(Integer defShopId, Integer userId) {
        personMapper.updateAllDefShopId(userId);
        System.out.println("asdasd");
        personMapper.updateDefShopId(defShopId, userId);
    }

    @Override
    public List<OrderList> selectOrdersByUserId(Integer userId) {
        //根据用户名找订单
        List<Orders> orders = personMapper.getOrders(userId);


        Set orderNum = new HashSet();
        for (int i = 0; i < orders.size(); i++) {
            orderNum.add(orders.get(i).getOrderNum());
        }
        Iterator<Object> it = orderNum.iterator();
        List<OrderList> orderLists = new ArrayList<>();
        while (it.hasNext()) {
            OrderList orderList = new OrderList();
            orderList.setOrder(new ArrayList<Orders>(getOrdersByOrderNumAndUserId(it.next() + "", userId)));
            orderLists.add(orderList);
        }
        Date date[] = new Date[orderLists.size()];
        for (int i = 0; i < orderLists.size(); i++) {
            date[i] = orderLists.get(i).getOrder().get(0).getCreateTime();
        }
        Arrays.sort(date);
        List<OrderList> orderListsSort = new ArrayList<>();
        for (int i = date.length - 1; i >= 0; i--) {
            for (int j = 0; j < orderLists.size(); j++) {
                if (orderLists.get(j).getOrder().get(0).getCreateTime() == date[i]) {
                    orderListsSort.add(orderLists.get(j));
                }
            }
        }
        return orderListsSort;
    }

    @Override
    public List<Orders> getOrdersByOrderNumAndUserId(String orderNum, Integer userId) {
        return personMapper.getOrdersByOrderNumAndUserId(orderNum, userId);
    }

    @Override
    public void deleteOrderByuserIdAndOrderNum(String orderNum, Integer userId) {
        personMapper.deleteOrderByuserIdAndOrderNum(orderNum, userId);
    }

    @Override
    public UserInformation queryUserInfoByUserId(Integer userId) {
        return personMapper.queryUserInfoByUserId(userId);
    }

    @Override
    public void insertInitUserByUserId(Integer userId, String phone) {
        //设置用户初始属性
        UserInformation newUser = new UserInformation();
        newUser.setUserId(userId);
        newUser.setNickName("小橘");
        //生成随机初始用户ID
        Random random = new Random(10);
        int y = 0;
        do {
            y = random.nextInt(100000);
        } while (y < 10000);
        newUser.setName("用户" + y);
        newUser.setPhoneNum(phone);
        newUser.setGender(3);
        newUser.setAccountBalance(0);
        newUser.setBirthday(new Date());
        newUser.setEmail("");
        newUser.setTotalPoints(0);
        newUser.setUserProfile("../images/getAvatar.do.jpg");

        //增加初始化新用户
        personMapper.insertInitUserByUserId(newUser);
    }

    @Override
    public List<Comments> queryCommentsByUserId(Integer userId) {
        return personMapper.selectCommentsByUserId(userId);
    }

    @Override
    public List<Product> queryProductByUserId() {
        return personMapper.queryProductByUserId();
    }
}
